/**
 * Copyright 2007 Luke Pillow
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package com.orsomethinglikethat.flex.filemaker
{
	public dynamic class Record
	{
		private var fieldMeta:XMLList;
		
		public var RECORDID:String;
		public var MODID:String;
		
		public var fields:Array = new Array();
		public var values:Array = new Array();
		
		public function Record( row:XML, fieldMeta:XMLList )
		{
			super();
			this.fieldMeta = fieldMeta;
			this.initialize( row );
		}
		
		private function initialize( row:XML ):void
		{
			this.RECORDID = row.attribute( "RECORDID" );
			this.MODID = row.attribute( "MODID" );
			
			var cols:XMLList = row.children();
			
			for( var i:int = 0; i < this.fieldMeta.length(); i++ )
			{
				trace( this.fieldMeta[i].attribute("NAME") + "=" + this.colData(cols[i]) );
				this.setPropertyValue( this.fieldMeta[i].attribute("NAME"), this.colData(cols[i]) );
			}
		}
		
		private function setPropertyValue( fieldName:String, value:String ):void
		{
			var index:int = fieldName.indexOf( "::" );
			
			if( index != -1 )
			{
				var aggregateName:String = fieldName.substring( 0, index );
				var propertyName:String = fieldName.substring( index + 2, fieldName.length );
				
				if( this[aggregateName] == null )
				{
					this[aggregateName] = new ReadOnlyObject();
				}
				
				this[aggregateName][propertyName] = value;
			}
			else
			{
				this[fieldName] = value;
			}
			
			this.fields.push( fieldName );
			this.values.push( value );
		}
		
		private function colData( col:XML ):String
		{
			if( col.children().length() == 1 )
			{
				return col.children()[0].text();
			}
			else
			{
				return null;
			}
		}
	}
}